import axios from 'axios'

const http = axios.create({
    timeout: 1000 * 120,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
/**
 * 请求拦截
 */
http.interceptors.request.use(
    (config) => {
        config.headers['token'] = localStorage.getItem('token') // 请求头带上token
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

/**
 * 响应拦截
 */
http.interceptors.response.use(
    (response) => {
        const res = response.data
        if (res.code == 1) {
            return res
        } else {
            return Promise.reject(res.msg || 'error')
        }
    },
    (error) => {
        if (error.response && error.response.status == 502) {
            alert(error)
        }

        return Promise.reject(error)
    }
)

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
    return params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
    return JSON.stringify(data)
}

export default http
